package com.moon.interview.aop;

import cn.hutool.core.date.StopWatch;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.UUID;

/**
 * 请求响应日志 Aop
 * @author MoonX
 */
@Aspect
@Component
@Slf4j
public class LogInterceptor {

    private final HttpServletRequest httpServletRequest;

    public LogInterceptor(HttpServletRequest httpServletRequest) {
        this.httpServletRequest = httpServletRequest;
    }

    @Around("execution(* com.moon.interview.controller.*.*(..))")
    public Object doInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        // 开始时间
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 生成请求唯一Id  (流水号)
        String requestId = UUID.randomUUID().toString();
        // 请求路径url
        String url = httpServletRequest.getRequestURI();
        // 获取请求参数
        Object[] args = joinPoint.getArgs();
        String reqParam = "[" + StringUtils.join(args,",") + "]";
        // 输出请求日志
        log.info("请求日志，id：{}， path：{}，ip：{}，params:{}", requestId, url, httpServletRequest.getRemoteHost(), reqParam);
        // 执行原方法
        Object result = joinPoint.proceed();
        // 获取执行时间
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        // 输出响应日志
        log.info("响应日志，id：{}， cost：{} ms，result{}", requestId, totalTimeMillis, result);
        return result;
    }
}
